package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "wx")
public class WeChatUtils {
    private String AppID;
    private String AppSecret;
    public  String getOpenId(String code) throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder("https://api.weixin.qq.com/sns/jscode2session");
        uriBuilder.setParameter("appid", AppID);
        uriBuilder.setParameter("secret", AppSecret);
        uriBuilder.setParameter("js_code", code);
        uriBuilder.setParameter("grant_type", "authorization_code");

        HttpGet httpGet = new HttpGet(uriBuilder.build());

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            String respStr = EntityUtils.toString(entity);
            JSONObject jsonObject = JSON.parseObject(respStr, JSONObject.class);

            String openid = jsonObject.getString("openid");
            return openid;

        }
    }
}